package com.nexus.ai.rag;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 检索增强
 * @Date 2025/9/29 03:51
 * @Author luzhengning
 **/
@Service
public class NexusAiAdvisorService {

    @Autowired
    private VectorStore vectorStore;

    @Autowired
    private ChatClient chatClient;

    public String rag(String msg){
        //文字模板，选填
        String template=
                "以下为相关背景(上下文)信息，" +
                        "---------------------------" +
                        "{question_answer_context}" +
                        "---------------------------" +
                        "要求：回答需使用精准而简洁的回答，" +
                        "如果无法回答，请说明‘信息不足，暂时无法提供答案’，" +
                        "避免使用诸如‘根据上下文...’或‘提供的信息’这样的描述。" +
                        "问题：{query}";
        PromptTemplate customTemplate = PromptTemplate.builder().template(template).build();
        //创建Advisor
        Advisor advisor= QuestionAnswerAdvisor.builder(vectorStore)
                .searchRequest(SearchRequest.builder()
                        .similarityThreshold(0.2)   //相似度阈值
                        .topK(1)    //找出相似度最好的一条
                        //.filterExpression("source=='甘肃省兰州市'")   //元数据查询
                        .build()
                )
                .promptTemplate(customTemplate)
                .build();

        ChatClient.CallResponseSpec call = chatClient.prompt()
                .user(msg)
                .advisors(advisor)  //使用Advisor实现Rag增强查询
                .call();
        String content = call.content();
        return content;
    }
}
